package com.iot08.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.api.utils.wxpay.MD5Util;
import com.iot08.common.config.mongodb.query.UpdateVO;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.app.Account;
import com.iot08.common.entity.app.Device;
import com.iot08.common.entity.app.DeviceSanWord;
import com.iot08.common.entity.app.HCYAuth;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version 1.0
 * @Description:
 * @author: Weichao
 * @time: 2023/8/31 16:24
 */
@Slf4j
@Service
public class DeviceSanWordService extends BaseService<DeviceSanWord> {

    /**
     * 生词本名称
     */
    public static String newWordsNotebookName = "newWordsNotebook.json";
    /**
     * 扫描本名称
     */
    public static String scanWordNotebookName = "scanWordNotebook.json";

    @Value("${deviceSanWord.updateDayLimit:50}")
    public String deviceSanWordUpdateDauLimit;
    public String deviceSanWordUpdateDayCountKey = "deviceSanWordUpdateDayCount:";


    @Resource
    private HCYAuthService hcyAuthService;


    /**
     * 批量上传 单词
     * @param imei
     * @param addList 已经保存到数据库中的单词数组
     * @param openid
     */
    public void addListAndUpCloud(String imei, JSONArray addList, String openid) {

        HCYAuth auth = hcyAuthService.findById(openid);
        if(auth != null && auth.getIsOff() == 0 && auth.getAccesstoken() != null){
            //没有手动关闭 且 accesstoken 有值
            boolean upRes = postWordToCloud(addList, auth, openid);
            if(upRes) {
                Date addTime = new Date();
                //上传成功
                for (int i = 0; i < addList.size(); i++) {
                    DeviceSanWord item = addList.getObject(i, DeviceSanWord.class);
                    item.setIsUpdateHCY(1);
                    item.setUpdateCloudTime(addTime);
                    this.save(item);
                }

                log.info("生词 上传云盘成功 imei:{} openid:{}", imei, openid);
            }else{
                log.info("生词 上传云盘失败 imei:{} openid:{}", imei, openid);
            }
        }
    }
    /**
     * 添加记录
     */
    public DeviceSanWord add(String imei, JSONObject data) {
        /*
         * data:{
         *
         *         "type":1,//1生词记录，2扫描记录
         *
         *         "srcText":"原文",
         *
         *         "transText":"译文",
         *
         *         "time":"20230505093823"//yyyyMMddHHmmss
         *
         *       }
         * */
        String srcText = data.getString("srcText");
        if (srcText == null) {
            return null;
        }
        String md5Id = MD5Util.md5Encode(srcText, "utf8");
        DeviceSanWord ob = this.findById(imei + "&" + md5Id);
        if (ob == null) {
            ob = new DeviceSanWord();
            ob.setId(imei + "&" + md5Id);
            ob.setImei(imei);
            ob.setCreatetime(new Date());
        }
        ob.setType(data.getInteger("type"));
        ob.setSrcText(data.getString("srcText"));
        ob.setTransText(data.getString("transText"));
        ob.setTime(data.getString("time"));
        ob.setModifytime(new Date());
        ob.setExpiryAt(DateUtil.addDay(new Date(), Const.WORD_TIME_DAY));
        return this.save(ob);
    }
    public long getCount(String imei, String startDate, String endDate) {
        Query query = new Query(Criteria.where("i").is(imei).and("time").gte(startDate).lte(endDate));
        return this.count(query);
    }


    public JSONArray listUploadRecords(String imei, int aType, String dateStr, Integer page, Integer num){
        //yyyyMMdd //eg: 20230912
        String startDate = dateStr+"000000";
        String endDate = dateStr+"235959";
        Query query = new Query(Criteria.where("i").is(imei).and("isUpdateHCY").is(1).and("time").gte(startDate).lte(endDate));
        query = query.with(Sort.by(Sort.Order.desc("time"))).skip((long) page *num).limit(num);

        //modifytime
        JSONArray upWordList = new JSONArray();
        /*
        upWordList:[
            {
                "id": "",
                "type":1,//1生词记录，2扫描记录
                "srcText":"原文",
                "transText":"译文",
                "time":"20230505093823",//yyyyMMddHHmmss
                "updateTime": 1694503443727 //上传时间
            },
            ...
        ]
        */
        List<DeviceSanWord> records = this.find(query);
        for (int i = 0; i < records.size(); i++) {
            DeviceSanWord item = records.get(i);
            JSONObject itemOB = new JSONObject();
            if(aType == 1){
                itemOB.put("id",item.getId());
                itemOB.put("type",item.getType());
                itemOB.put("srcText",item.getSrcText());
                itemOB.put("transText",item.getTransText());
                itemOB.put("time",item.getTime()); //扫描笔记录时间
                itemOB.put("modifytime",item.getModifytime().getTime()); //上次的修改时间
                upWordList.add(itemOB);
            }
        }
        log.info("获取云生词上传记录列表 imei:{} aType:{}  records.size():{} upWordList:{} ", imei, aType, records.size(), upWordList);
        return upWordList;
    }
    /**
     * 获取生词列表
     * @param imei imei
     * @param startDate 起始时间 //yyyyMMddHHmmss
     * @return
     */
    public Object listData(String imei, int aType, String startDate, String endDate) {
        Query query = null;
        if(StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)){
            //全部
            query = new Query(Criteria.where("i").is(imei));
        }else{
            query = new Query(Criteria.where("i").is(imei).and("time").gte(startDate).lte(endDate));
        }

        query = query.with(Sort.by(Sort.Order.desc("time")));

        //modifytime
        JSONArray dataList = new JSONArray();
        /*
        inGetCount == 0
        dataList:[
            {
                "id": "",
                "type":1,//1生词记录，2扫描记录
                "srcText":"原文",
                "transText":"译文",
                "time":"20230505093823"//yyyyMMddHHmmss
            },
            ...
        ]

        inGetCount == 1

        dataList:[
            {
                "date": "2023-09-12",
                "count": 100
            },
            ...
        ]
        */
        try{
            List<DeviceSanWord> records = this.find(query);
            JSONObject dateMap = new JSONObject();
            // 创建一个格式化日期时间的 SimpleDateFormat 对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            for (int i = 0; i < records.size(); i++) {
                DeviceSanWord item = records.get(i);
                JSONObject itemOB = new JSONObject();
                if(aType == 1){
                    itemOB.put("id",item.getId());
                    itemOB.put("type",item.getType());
                    itemOB.put("srcText",item.getSrcText());
                    itemOB.put("transText",item.getTransText());
                    itemOB.put("time",item.getTime()); //扫描笔记录时间
                    itemOB.put("modifytime",item.getModifytime().getTime()); //上次的修改时间
                    itemOB.put("isUpdateHCY",item.getIsUpdateHCY()); //是否上传云盘
                    dataList.add(itemOB);
                }else{
                        // 将时间字符串解析为日期对象
                        Date date = sdf.parse(item.getTime());
                        // 根据日期对象提取年、月、日信息
                        SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
                        String yearMonthDay = yearMonthDayFormat.format(date);
                        String year = yearMonthDay.split("-")[0];
                        String month = yearMonthDay.split("-")[1];
                        String day = yearMonthDay.split("-")[2];
                        // 将时间字符串添加到对应的年月日键下
                        if (!dateMap.containsKey(year)) {
                            JSONObject tempYearOb = new JSONObject();
                            JSONArray tempAayArr = new JSONArray();
                            tempAayArr.add(day);
                            tempYearOb.put(month, tempAayArr);
                            dateMap.put(year, tempYearOb);
                            continue;
                        }
                        JSONObject yearOB = dateMap.getJSONObject(year);
                        if (!yearOB.containsKey(month)) {
                            JSONArray tempAayArr = new JSONArray();
                            tempAayArr.add(day);
                            yearOB.put(month, tempAayArr);
                            continue;
                        }
                        JSONArray dayArr = yearOB.getJSONArray(month);
                        if(!dayArr.contains(day)){
                            dayArr.add(day);
                            yearOB.put(month, dayArr);
                            continue;
                        }
    //                    Integer num = dateMap.getInteger(yearMonthDay);
    //                    dateMap.put(yearMonthDay, num+1);
                }

            }
//            log.info("获取生词列表 imei:{} aType:{}  records.size():{} dataList:{} dateMap:{}", imei, aType, records.size(), dataList, dateMap);
            if(aType == 1){
                return dataList;
            }else{
                return dateMap;
            }


        }catch (Exception e){
            return new JSONArray();
        }


    }


    /**
     * 删除对应Id的单词
     *
     * @param delIds 删除IDs
     */
    public void delWithIds(String delIds) {
        if(JSONArray.isValidArray(delIds)){
            JSONArray idArr = JSONArray.parseArray(delIds);
            //删除指定id
            Set<String> objectIdList = new HashSet<>();
            for (int i = 0; i < idArr.size(); i++) {
//                if (ObjectId.isValid(idArr.getString(i))) {
//                    objectIdList.add(new ObjectId(idArr.getString(i)));
//                }
                objectIdList.add(idArr.getString(i));
            }
            if (objectIdList.size() > 0) {
                this.delByIds(objectIdList);
            }
        }else{
            // 可能是单个
            this.delById(delIds);
        }

    }

    public Long getWeekUpdateWordWithDev(String imei, Date date){

//        Date date = DateUtil.strToDate(day, "yyyyMMdd");
        //获取星期  几（1-7表示周一到周日）
        int weekOfDate = DateUtil.getWeekOfDate(date);
        //本周第一天00:00:00
        String startDate = DateUtil.dateToStr(DateUtil.addDay(date, 1-weekOfDate), "yyyyMMdd");
        startDate = startDate+"000000";
        //本周第最后一天23:59:59
        String endDate = DateUtil.dateToStr(DateUtil.addDay(date, 7-weekOfDate), "yyyyMMdd");
        endDate = endDate+"235959";

        //day 最近的一周的情况
        Query query = new Query(Criteria.where("i").is(imei).and("time").gte(startDate).lte(endDate));
        return this.count(query);
    }

    public Long getAllWordWithDev(String imei){
        //全部
        Query query = new Query(Criteria.where("i").is(imei));
        return this.count(query);
    }




    /**
     * 云盘上传到云生词本
     * @param deviceSanWordList
     * @param auth
     * @param openid 用户ID
     * @return
     */
    public boolean postWordToCloud(JSONArray deviceSanWordList, HCYAuth auth, String openid){
        //type 1:生词本 2:扫描本
        return hcyAuthService.uploadWord(deviceSanWordList, auth, 1, openid);
    }

    public static void main(String[] args) throws Exception {
        String[] timeStrings = {
                "20230909081030",
                "20230909121545",
                "20230910093015",
                // 添加更多时间字符串
        };
        JSONObject dateMap = new JSONObject();
        // 创建一个格式化日期时间的 SimpleDateFormat 对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        for (int i = 0; i < timeStrings.length; i++) {

            // 将时间字符串解析为日期对象
            Date date = sdf.parse(timeStrings[i]);
            // 根据日期对象提取年、月、日信息
            SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
            String yearMonthDay = yearMonthDayFormat.format(date);
            String year = yearMonthDay.split("-")[0];
            String month = yearMonthDay.split("-")[1];
            String day = yearMonthDay.split("-")[2];

            // 将时间字符串添加到对应的年月日键下
            if (!dateMap.containsKey(year)) {
                JSONObject tempYearOb = new JSONObject();
                JSONArray tempAayArr = new JSONArray();
                tempAayArr.add(day);
                tempYearOb.put(month, tempAayArr);
                dateMap.put(year, tempYearOb);
                continue;
            }
            JSONObject yearOB = dateMap.getJSONObject(year);
            if (!yearOB.containsKey(month)) {
                JSONArray tempAayArr = new JSONArray();
                tempAayArr.add(day);
                yearOB.put(month, tempAayArr);
                continue;
            }
            JSONArray dayArr = yearOB.getJSONArray(month);
            if(!dayArr.contains(day)){
                dayArr.add(day);
                yearOB.put(month, dayArr);
                continue;
            }
        }
        log.info("dateMap:{}",dateMap);
    }
}
